<script setup lang="ts">
import { PriceType } from "@/types/trade.types";
import { type InputInstance, type PopoverInstance } from "element-plus";
import { ref } from "vue";
import { useTradeStore } from "@/store/modules/tradeStore";
import { storeToRefs } from "pinia";

defineOptions({
  name: "price-input"
});

const trade = useTradeStore();
const { contract, price, tick } = storeToRefs(trade);

const popoverRef = ref<PopoverInstance>();
const manualInputRef = ref<InputInstance>();
const selectedPriceType = ref<PriceType>(PriceType.QUEUE);
const manualPrice = ref<number>(0);

const onPriceButtonClick = (priceType: PriceType) => {
  selectedPriceType.value = priceType;
  if (priceType === PriceType.LIMIT) {
    manualPrice.value = tick.value?.last_price ?? 0;
    manualInputRef.value?.focus();
  } else {
    price.value = priceType;
    popoverRef.value?.hide();
  }
};

const onConfirm = () => {
  price.value = manualPrice.value.toString();
  popoverRef.value?.hide();
};
</script>

<template>
  <div
    class="w-full rounded-sm border border-gray-300 text-center text-sm shadow-sm hover:cursor-pointer"
  >
    <el-popover
      ref="popoverRef"
      width="300"
      trigger="click"
      placement="bottom-start"
      :show-after="0"
      :hide-after="0"
      ><template #reference>
        <div>{{ price }}</div>
      </template>
      <div name="price-input-popover">
        <div class="px-1 pb-1 text-xs">输入价格</div>

        <!-- 预设价格 -->
        <div class="grid w-full grid-cols-4 gap-1">
          <el-button
            v-for="(label, key) in PriceType"
            :key="key"
            size="small"
            class="m-0!"
            plain
            :type="selectedPriceType === label ? 'primary' : 'default'"
            @click="onPriceButtonClick(label)"
          >
            {{ label }}
          </el-button>
        </div>
        <!-- 输入价格 -->
        <div class="flex-bc mt-3">
          <el-input-number
            ref="manualInputRef"
            v-model="manualPrice"
            :min="0"
            :disabled="selectedPriceType !== PriceType.LIMIT"
            :step="contract?.pricetick ?? 1"
            step-strictly
          />
          <div class="text-xs text-gray-500">
            {{ contract?.pricetick }}<span class="text-sm">/tick</span>
          </div>
          <el-button type="primary" @click="onConfirm">确定</el-button>
        </div>
      </div>
    </el-popover>
  </div>
</template>
